/*
 * Copyright 2018-2021 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.guerlab.spring.web.autoconfigure;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;

import java.util.Collections;

/**
 * 安全配置
 *
 * @author guer
 */
@Configuration
public class SecurityAutoconfigure extends WebSecurityConfigurerAdapter {

    private final ObjectProvider<CorsConfiguration> configProvider;

    public SecurityAutoconfigure(ObjectProvider<CorsConfiguration> configProvider) {
        this.configProvider = configProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic();

        http.csrf().disable();

        http.cors().configurationSource(request -> configProvider.getIfAvailable(DefaultCorsConfiguration::new));
    }

    private static class DefaultCorsConfiguration extends CorsConfiguration {

        public DefaultCorsConfiguration() {
            setAllowedOriginPatterns(Collections.singletonList(CorsConfiguration.ALL));
            setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
            setAllowedMethods(Collections.singletonList(CorsConfiguration.ALL));
            setMaxAge(1800L);
            setAllowCredentials(true);
        }
    }

}
